package com.ssyt.blog.core.sys.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ssyt.blog.core.common.PageModel;
import com.ssyt.blog.core.sys.entity.Category;
import com.ssyt.blog.core.sys.entity.Menu;
import com.ssyt.blog.core.sys.entity.User;
import com.ssyt.blog.core.sys.service.CategoryService;
import com.ssyt.blog.core.sys.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	private static Logger log = LogManager.getLogger(UserController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private CategoryService categoryService;

	@RequestMapping("/get/{id}")
	public String get(@PathVariable int id, Model model) throws Exception {
		log.info("进入到UserAction.get()方法查询单个对象结果");
		model.addAttribute("user", userService.get(id));
		return "success";
	}

	@ResponseBody
	@RequestMapping("/login")
	public Object login(String code, String password, HttpSession session)
			throws Exception {
		User user = userService.login(code, password);
		if (user != null) {
			session.setAttribute("user", user);
		}
		return user;
	}

	@RequestMapping("/logout")
	public String logout(HttpSession session) throws Exception {
		session.invalidate();
		return "redirect:/index.jsp";
	}

	@RequestMapping("/register")
	public String register(User user) throws Exception {
		user.setPhoto("statics/common/images/w11.png");
		user.setRoleId(2);
		Integer userId = userService.register(user);
		if (userId != null) {
			return "reg-success";
		} else {
			return "reg-fail";
		}

	}

	@ResponseBody
	@RequestMapping("/getMenu")
	public Object getMenu(Integer roleId) throws Exception {
		List<Menu> menuList = userService.getMenu(roleId);
		return menuList;
	}

	@ResponseBody
	@RequestMapping("/userInfo")
	public Object getUserList(Integer pageNo) throws Exception {
		PageModel<Object[]> userList = userService.getUserList(pageNo);
		String[] title = { "用户管理", "编号", "姓名", "账号", "操作" };
		List<Object> list = new ArrayList<>();
		list.add(title);
		list.add(userList);
		return list;
	}

	@ResponseBody
	@RequestMapping("/userInfoDelete")
	public void deleteUserInfo(Integer id) throws Exception {
		userService.deleteUserInfo(id);
	}

	@ResponseBody
	@RequestMapping("/getCategory")
	public Object getCategory(Integer userId) throws Exception {
		List<Category> list = categoryService.getCategory(userId);
		return list;
	}
}
